/**
 * Copyright 2013-2017 JueYue (qrb.jueyue@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.chcit.share.generator.utils;


import com.alibaba.fastjson.JSONObject;
import com.chcit.share.generator.factory.ParseFactory;
import com.chcit.share.generator.model.TemplateModel;
import com.chcit.share.generator.vo.GenerationEntity;
import com.chcit.share.generator.vo.TableModel;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

/**
 * @author liuyang
 */
public class CodeGenUtil {

    /**
     * 生产代码
     */
    public static JSONObject codeGen(GenerationEntity generationEntity, TableModel tableEntity, List<TemplateModel> fileList) {

        tableEntity.setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
        //Step 1 初始化数据库连接
        //ConnectionUtil.init(ReadTableFactory.getDeiver(model.getDbType()), model.getUrl(), model.getUsername(), model.getPasswd());
        //Step 2 读取数据源列表
        // GenBeanEntity tableEntity = ReadTableFactory.getReadTable(model.getDbType()).read(model.getDbName(),
        //          model.getTableName());
        //Step 3 解析模板,生产代码
        JSONObject json = new JSONObject();
        for (TemplateModel t : fileList) {
            json.put(getFileName(t, tableEntity.getClassName()), ParseFactory.getParse(t.getTemplateType()).parse(generationEntity, tableEntity, t));
        }
        return json;

    }

    public static String getFileName(TemplateModel templateModel, String ge) {
        if (templateModel.getFileName().endsWith("js")) {
            return String.format(templateModel.getFileName(), ge.toLowerCase());
        } else if (templateModel.getFileName().endsWith("html")) {
            return String.format(templateModel.getFileName(), ge.toLowerCase());
        } else if (templateModel.getFileName().endsWith("vue")) {
            return String.format(templateModel.getFileName(), ge.toLowerCase());
        } else if (templateModel.getFileName().endsWith("xml")) {
            return String.format(templateModel.getFileName(), ge);
        } else {
            return String.format(templateModel.getFileName(), ge);
        }
    }


}
